import { defineStore } from 'pinia';
import { GlobalSizeStorage } from '@/utils/storage/localStorage';

/**
 * 注册全局状态相关的store
 */
export const useGlobalStore = defineStore(
  'global',
  () => {
    /** 全局大小 */
    const globalSize = ref<$GlobalSize>(new GlobalSizeStorage().get());

    /** 设置全局大小 */
    function setGlobalSize(): void {
      globalSize.value = globalSize.value === 'small' ? 'default' : 'small';
      new GlobalSizeStorage().set(globalSize.value);
    }

    watch(
      () => globalSize.value,
      (size) => {
        const times = size === 'small' ? 1 : size === 'large' ? 3 : 2;
        document.documentElement.style.setProperty('--my-change-1x-size', `${times}px`);
        document.documentElement.style.setProperty('--my-change-2x-size', `${2 * times}px`);
        document.documentElement.style.setProperty('--my-change-3x-size', `${3 * times}px`);
        document.documentElement.style.setProperty('--my-change-4x-size', `${4 * times}px`);
      },
      {
        immediate: true,
      }
    );

    /** 全局主题 */
    const globalTheme = ref<$GlobalTheme>(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');

    /** 设置全局主题 */
    function setGlobalTheme(theme: $GlobalTheme = globalTheme.value) {
      globalTheme.value = theme;
    }

    watch(
      () => globalTheme.value,
      (theme) => {
        if (theme === 'light') {
          document.documentElement.classList.remove('dark');
          document.documentElement.classList.add('light');
        } else if (theme === 'dark') {
          document.documentElement.classList.add('dark');
          document.documentElement.classList.remove('light');
        }
      },
      {
        immediate: true,
      }
    );

    /** 监听主题颜色变化 */
    window.matchMedia('(prefers-color-scheme: dark)').addListener((e) => {
      useGlobalStore().setGlobalTheme(e.matches ? 'dark' : 'light');
    });

    return {
      /** 全局大小 */
      globalSize,
      /** 全局主题 */
      globalTheme,
      /** 设置全局大小 */
      setGlobalSize,
      /** 设置全局主题 */
      setGlobalTheme,
    };
  },
  {
    /** 持久化储存 依赖 pinia-plugin-persistedstate 插件 */
    persist: {
      key: 'my_pinia_global',
      pick: ['globalTheme'],
      storage: window.sessionStorage,
    },
  }
);
